package com.bknow.controller;

import java.util.List;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.bknow.annotation.ParamValid;
import com.bknow.model.CodeUserInfo;
import com.bknow.model.PageBean;
import com.bknow.model.ResultBean;
import com.bknow.model.UserInfo;
import com.bknow.service.UserService;
import com.bknow.util.Md5Util;
import com.bknow.validate.SendSms;

@Controller
public class UserController {

	@Autowired
	private UserService userSerivce;

	@PostMapping("isUserExist")
	public @ResponseBody ResultBean<Boolean> isUserExist(@RequestBody UserInfo userInfo) {

		if (!StringUtils.isEmpty(userInfo)) {
			UserInfo user = userSerivce.isUserExist(userInfo.getuName());
			if (user != null) {
				// 用户存在，返回false
				return new ResultBean<Boolean>(401, "用户已存在", false);
			} else {
				// 用户不存在，返回true
				return new ResultBean<Boolean>(200, "用户名可以使用", true);
			}
		} else
			throw null;
	}

	@PostMapping("/user")
	@ResponseBody
	public ResultBean<UserInfo> user(@RequestBody UserInfo userInfo, HttpSession session) {
		if (StringUtils.isEmpty(userInfo)) {
			return new ResultBean<UserInfo>(401, "用户输入不能为空", null);// 401
		} else {
			userInfo.setuPwd(Md5Util.getMd5(userInfo.getuPwd()));
			UserInfo user = userSerivce.findUserByNameAndPwd(userInfo);
			if (user != null) {
				session.setAttribute("userInfo", userInfo);
				return new ResultBean<UserInfo>(200, "success", user);
			} else {
				return new ResultBean<UserInfo>(401, "用户名或密码不正确", user);
			}

		}
	}

	@GetMapping("getUserMsg")
	@ResponseBody
	public ResultBean<UserInfo> getUserMsg(HttpSession hs) {
		if (hs.getAttribute("userInfo") == null) {
			return new ResultBean<UserInfo>(401, "fail", null);
		} else {
			UserInfo u = (UserInfo) hs.getAttribute("userInfo");
			UserInfo user = userSerivce.findUserByName(u.getuName());
			return new ResultBean<UserInfo>(200, "success", user);
		}
	}

	@GetMapping("alluser")
	@ResponseBody
	public ResultBean<List<UserInfo>> alluser(int page, int limit) {
		PageBean<List<UserInfo>> pb = userSerivce.findAllUser(page, limit);
		pb.setMsg("所有用户");
		pb.setStatus(200);
		return pb;
	}

	@GetMapping("/main")
	@ResponseBody
	public String toMain(HttpSession session) {
		return "redirect:http://localhost/main.html";
	}

	@GetMapping("isEmailExist")
	public @ResponseBody ResultBean<Boolean> isEmailExist(@RequestBody UserInfo userInfo) {

		if (!StringUtils.isEmpty(userInfo)) {
			UserInfo user = userSerivce.isEmailExist(userInfo.getuEmail());
			if (user != null) {
				// 邮箱存在，返回false
				return new ResultBean<Boolean>(401, "fail", false);
			} else {
				// 邮箱不存在，返回true
				return new ResultBean<Boolean>(200, "success", true);
			}
		} else
			return null;

	}

	@PostMapping("getValidate")
	public @ResponseBody ResultBean<Boolean> getValidate(@RequestBody UserInfo userInfo, HttpSession hs)
			throws ServerException, ClientException {

		if (!StringUtils.isEmpty(userInfo.getuPhone())) {
			UserInfo user = userSerivce.isPhoneExist(userInfo.getuPhone());
			if (user != null) {
				return new ResultBean<Boolean>(501, "手机号已存在,请换个手机号", false);
			} else {
				String smsCode = SendSms.createCode();
				boolean result = SendSms.getSms(userInfo.getuPhone(), smsCode);
				if (result) {// true表示短信发送成功
					hs.setAttribute("smsCode", smsCode);
					// hs.setMaxInactiveInterval(60);设置验证码60s过期
					return new ResultBean<Boolean>(200, "已发送", true);
				} else {// false表示短信发送失败
					return new ResultBean<Boolean>(401, "发送失败", false);
				}
			}
		} else {
			return new ResultBean<Boolean>(501, "手机号不能为空", false);
		}

	}

	@PostMapping("regist")
	public @ResponseBody ResultBean<Boolean> regist(@RequestBody CodeUserInfo userInfo, HttpSession hs) {
		String code = userInfo.getuCode();
		if (!StringUtils.isEmpty(code) && code.equals(hs.getAttribute("smsCode"))) {
			if (!StringUtils.isEmpty(userInfo)) {
				userInfo.setuPwd(Md5Util.getMd5(userInfo.getuPwd()));// 将密码md5加密
				userInfo.setuHeadimg("default.png");
				int result = userSerivce.regist(userInfo);
				if (result == 1) {
					// 影响行数为1，注册成功
					return new ResultBean<Boolean>(200, "注册成功", true);
				} else {
					return new ResultBean<Boolean>(401, "注册失败", false);
				}
			} else {
				return new ResultBean<Boolean>(501, "用户信息不能为空", false);
			}
		} else {
			return new ResultBean<Boolean>(501, "验证码不能为空", false);
		}
	}

	@GetMapping("logout")
	public @ResponseBody ResultBean<Boolean> logout(HttpSession hs) {
		hs.invalidate();
		return new ResultBean<Boolean>(200, "success", null);

	}

	// 删除用户
	@DeleteMapping("user/{id}")
	@ResponseBody
	public ResultBean<Boolean> deleteUser(@PathVariable("id") Integer uId) {
		int flag = userSerivce.deleteUserByUid(uId);
		if (flag > 0) {
			return new ResultBean<>(200, "删除成功", true);
		} else {
			return new ResultBean<>(401, "删除失败", false);
		}

	}

	// 修改用户
	@PutMapping("user")
	@ResponseBody
	@ParamValid
	public ResultBean<Boolean> modifyUser(@Valid @RequestBody UserInfo userInfo, BindingResult bindResult) {
		int flag = userSerivce.modifyUser(userInfo);
		if (flag > 0) {
			return new ResultBean<>(200, "修改成功", true);
		} else {
			return new ResultBean<>(401, "修改失败", false);
		}
	}

	// 修改用户
	@DeleteMapping("users")
	@ResponseBody
	public ResultBean<Boolean> deleteUsers(@RequestBody String ids) {
		int flag = userSerivce.patchDeleteUser(ids);
		System.out.println(flag);
		if (flag > 0) {
			return new ResultBean<>(200, "批量删除成功", true);
		} else {
			return new ResultBean<>(401, "批量删除失败", false);
		}
	}

}
